package com.loubobooo.personal.blog.controller.portal;

import com.loubobooo.personal.blog.common.Const;
import com.loubobooo.personal.blog.entity.vo.*;
import com.loubobooo.personal.blog.service.*;

import com.loubobooo.personal.blog.util.JsonUtil;
import com.loubobooo.personal.blog.util.RedisPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 用户的controller
 */
@Controller public class IndexController {

    @Autowired private ArticleService articleService;

    @Autowired private LinkService linkService;

    @Autowired private NoticeService noticeService;

/*    @ModelAttribute public void init(Model model) {
        //友情链接
        List<LinkVO> linkVOList = linkService.listLink(1);
        model.addAttribute("linkVOList", linkVOList);

        //公告
        List<NoticeVO> noticeVOList = noticeService.listNotice(1);
        model.addAttribute("noticeVOList", noticeVOList);
    }*/

    //首页显示
    @RequestMapping("/") public ModelAndView IndexView() {
        ModelAndView modelAndView = new ModelAndView();
        //文章列表
        int pageSize = 10;

        String cacheValue = RedisPoolUtil.get(Const.REDIS_KEY.ALL_ARTICLE);
        List<ArticleListVo> articleListVoList = null;
        if(StringUtils.isBlank(cacheValue)){
            articleListVoList = articleService.listArticleByPage(1, null, pageSize);
            // 存储到redis中
            cacheValue = JsonUtil.obj2String(articleListVoList);
            RedisPoolUtil.set(Const.REDIS_KEY.ALL_ARTICLE, cacheValue);
        }else{
            articleListVoList = JsonUtil.string2Obj(cacheValue, new TypeReference<List<ArticleListVo>>(){});
        }

        modelAndView.addObject("articleListVoList", articleListVoList);
        modelAndView.setViewName("/Home/index");
        return modelAndView;
    }

    //文章分页显示
    @RequestMapping("p/{pageNo}")
    //适合RESTful
    public ModelAndView ArticleListByPageView(@PathVariable("pageNo") Integer pageNo) {
        ModelAndView modelAndView = new ModelAndView();
        //设置每页显示的数量
        int pageSize = 10;
        List<ArticleListVo> articleListVoList = articleService.listArticleByPage(1, pageNo, pageSize);
        modelAndView.addObject("articleListVoList", articleListVoList);
        modelAndView.setViewName("Home/index");
        return modelAndView;//不会被解析为跳转路径，而是直接写入HTTP response body中
    }

}




